package test

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

const (
	SECRETKEY = "yshopmini" //私钥
)

// 自定义Claims
type CustomClaims struct {
	Uid   int64
	Scope int64
	UName string
	jwt.StandardClaims
}

// .withClaim("uid", uid)
// .withClaim("scope", scope)
// .withClaim("uName", uName)
// .withExpiresAt(map.get("expiredTime"))
// .withIssuedAt(map.get("now"))
func createToken() string {
	//生成token 过期时间
	maxAge := 60 * 60 * 24
	customClaims := &CustomClaims{
		Scope: 8888,
		UName: "xiaobao",
		Uid:   1074, //用户id
		StandardClaims: jwt.StandardClaims{
			//ExpiresAt: 1694253817, //测试过期时间，使用中药创建一个超过当前的时间
			ExpiresAt: time.Now().Add(time.Duration(maxAge) * time.Second).Unix(), // 过期时间，必须设置
			Issuer:    "jerry",                                                    // 非必须，也可以填充用户名，
		},
	}
	//采用HMAC SHA256加密算法
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, customClaims)
	tokenString, err := token.SignedString([]byte(SECRETKEY))
	if err != nil {
		fmt.Println(err)
		return ""
	}
	return tokenString
}
func main() {
	//tokenString := createToken()
	tokenString := "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1aWQiOjEwNzQsInNjb3BlIjo4LCJleHAiOjE2OTQzMzAxNTEsImlhdCI6MTY5NDI0Mzc1MSwic2NlbmUiOiJoNSJ9.GPu7J4t-5uXKV0DdJYzzaF66cseoOr3MrVLWLsJ8Vqk"
	fmt.Printf("token: %v\n", tokenString)

	//解析token
	ret, err := ParseToken(tokenString)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Printf("userinfo:%v,%v,%v,%v,%v\n", ret.Uid, ret.Scope, ret.UName, ret.ExpiresAt, ret.IssuedAt)

}

// 解析token
func ParseToken(tokenString string) (*CustomClaims, error) {
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(SECRETKEY), nil
	})
	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	} else {
		return nil, err
	}
}
